//
//  BaseViewController.m
//  dangdang
//
//  Created by air on 15/12/9.
//  Copyright © 2015年 luweijie. All rights reserved.
//

#import "BaseViewController.h"

@interface BaseViewController ()

@property (nonatomic, assign) CGFloat keyBoardHeight;

@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置后退UIBarButtonItem字符为空
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    //设置背景颜色为浅灰
    self.view.backgroundColor = [UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:239.0/255.0 alpha:1.0];
    //估算键盘高度
    if ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait){
        _keyBoardHeight = 258;
    }
    else{
        _keyBoardHeight = 194;
    }
}

#pragma-mark KeyboardNotification
-(void)viewWillAppear:(BOOL)animated
{
    [self registerForKeyboardNotifications];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)registerForKeyboardNotifications
{
    //使用NSNotificationCenter 鍵盤出現時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillShow:)
     
                                                 name:UIKeyboardWillShowNotification object:nil];
    
}

//实现当键盘出现的时候计算键盘的高度大小。用于输入框显示位置
- (void)keyboardWillShow:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    //kbSize即為鍵盤尺寸 (有width, height)
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//得到鍵盤的高度
    //    NSLog(@"hight_hitht:%f",kbSize.height);
    _keyBoardHeight = kbSize.height;
    
}

#pragma-mark textFieldDelegate

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSInteger correctedValue = 0;
    if (self.navigationController != nil) {
        correctedValue = 44;
    }
    
    CGFloat controlY = [self.view convertRect:textField.frame fromView:textField.superview].origin.y;
    CGFloat controlHeight = textField.frame.size.height;
    
    
    CGFloat offset = self.view.frame.size.height - controlY - controlHeight - _keyBoardHeight;
    //键盘高度258
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset < 0)
        self.view.frame = CGRectMake(0.0f, offset, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}



//当用户按下return键或者按回车键，keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

//UIApplicationWillChangeStatusBarOrientationNotification

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    CGFloat correctedValue = 0;
    if (self.navigationController != nil) {
        CGFloat navigationBarHeight = self.navigationController.navigationBar.bounds.size.height;
        if ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait) {
            correctedValue = 20 + navigationBarHeight;
        }
        else{
            correctedValue = navigationBarHeight;
        }
    }
//    self.view.frame =CGRectMake(0, correctedValue, self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

-(void)alertViewShowWithAlertString:(NSString *)alertString
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:self.title message:alertString preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertVC addAction:action];
    [self presentViewController:alertVC animated:NO completion:nil];
}

#pragma-mark AFNetWorking

-(void)postRequestWithMethodName:(NSString *)methodName andParams:(NSDictionary *)params andSender:(id)sender
{
    NSString *requestString = [NSString stringWithFormat:@"%@%@",URLDoman,methodName];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer.timeoutInterval = TimeoutInterval;
    
    __weak typeof(self) weakSelf = self;
    if (requestString.length > 0 && requestString != nil) {
        [session POST:requestString parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            NSError *jsonError = nil;
            id dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&jsonError];
            if (jsonError != nil) {
                NSLog(@"json解析失败");
            }
            
            NSMutableDictionary *senderDic;
            if ([sender isKindOfClass:[NSDictionary class]]) {
                senderDic = [NSMutableDictionary dictionaryWithDictionary:sender];
            }
            else{
                senderDic = [NSMutableDictionary new];
            }
            [senderDic setObject:methodName forKey:TYPE];
            NSLog(@"dict = %@", dict);
            
            [LoadingView hideWithAnimated:YES];
            [weakSelf requestSuccessedWithResult:dict NSURLSessionTask:task sender:sender];
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            NSLog(@"error = %@", error);
            [weakSelf requestFailureWithNSURLSessionTask:task error:error sender:sender];
            [LoadingView hideWithAnimated:YES];
        }];
    }
}

- (void)requestSuccessedWithResult:(id)result NSURLSessionTask:(NSURLSessionTask *)task sender:(id)sender
{
    
}

- (void)requestFailureWithNSURLSessionTask:(NSURLSessionTask *)task error:(NSError *)error sender:(id)sender
{
    
}

@end
